package com.example.seckillweb.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: TODO
 * @author: uu
 * @date: 2023/12/18 19:57
 * @version: 1.0
 */
@RestController
public class SecKillController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RocketMQTemplate rocketMQTemplate;

    AtomicInteger userId = new AtomicInteger(1);

    @GetMapping("/seckill")
    public String secKillHandler(Integer goodsId){
        String uk = goodsId + "-" + userId.getAndIncrement();
        Boolean res = redisTemplate.opsForValue().setIfAbsent(uk, "exit");
        if (!res){
            return "已经参与！！！";
        }
        // TODO 同步库存
        System.out.println(redisTemplate.opsForValue().get("gd:" + goodsId));
        Long count = redisTemplate.opsForValue().decrement("gd:" + goodsId);
        if (count < 0){
            restore(uk, goodsId);
            return "库存不足";
        }
        // 发送mq消息
        rocketMQTemplate.asyncSend("seckillTopic", MessageBuilder
                        .withPayload(uk)
                        .build(),
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        System.out.println("发送成功");
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        restore(uk, goodsId);
                        System.out.println("发送失败" + throwable.getMessage());
                    }
                });

        return "抢购中";
    }

    private void restore(String uk, Integer goodId) {
        redisTemplate.opsForValue().increment("gd:" + goodId);
        userId.decrementAndGet();
        redisTemplate.delete(uk);
    }
}
